<template>
  <div class="unitList w100p h100p">
    <div class="flb bgWH headerTitle">
      <div class="total l20">
        <span>共</span>
        <span class="cYE mr2 ml2 f16">{{ unitList.length }}</span>
        <span>个计量单位</span>
      </div>
      <div class="cYE f14 l20" @click="showUnitPopup({}, 'add')">+添加单位</div>
    </div>
    <div class="content">
      <div class="contentBox">
        <div v-for="(el, index) in unitList" :key="index" class="contentItem" @click="showUnitPopup(el, 'update')">
          <van-swipe-cell>
            <van-cell :title="el.unit" :border="false" />
            <template #right>
              <van-button square type="danger" text="删除" @click.stop="delUnitInfo(el.id)" />
            </template>
          </van-swipe-cell>
        </div>
      </div>
    </div>
    <van-popup v-model="showUnit" round position="bottom">
      <van-form class="oyauto w100p" @submit="updateUnitInfo">
        <div class="flc mt10">
          <van-cell-group inset>
            <van-field v-model="unitInfo.unit" name="单位" label="单位" placeholder="单位" :rules="[{ required: true, message: '请填写单位' }]" />
          </van-cell-group>
        </div>
        <div style="margin: 16px;">
          <van-button color="#409eff" round block type="primary" native-type="submit">{{ unitStatus === 'add' ? '添加' : '更新' }}</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>
<script>
import { addUnit, deleteUnit, updateUnit, getAllUnit } from '../utils/api'
export default {
  data() {
    return {
      unitList: [],
      showUnit: false,
      unitInfo: {},
      unitStatus: 'add'
    }
  },
  mounted() {
    this.getUnitList()
  },
  methods: {
    // 弹框-增/改
    showUnitPopup(item, type) {
      this.unitInfo = JSON.parse(JSON.stringify(item))
      this.unitStatus = type
      this.showUnit = true
    },
    //增/改
    async updateUnitInfo() {
      this.showUnit = false
      if (this.unitStatus === 'add') {
        await addUnit({ ...this.unitInfo })
        this.$toast.success('单位信息添加成功！')
      } else {
        await updateUnit({ ...this.unitInfo })
        this.$toast.success('单位信息更新成功！')
      }
      this.getUnitList()
    },
    //删
    async delUnitInfo(id) {
      await this.$async.confirm({ message: '确认要删除单位信息吗？' })
      await deleteUnit({ id })
      this.$toast.success('单位信息删除成功！')
      this.getUnitList()
    },
    //查
    async getUnitList() {
      let res = await getAllUnit()
      this.unitList = res.data
    }
  }
}
</script>
<style lang="less" scoped>
.unitList {
  box-sizing: border-box;
  .content {
    padding-top: 8px;
    height: calc(100% - 32px);
    box-sizing: border-box;
    .contentBox {
      height: 100%;
      overflow-y: auto;
      .contentItem {
        width: 100%;
        height: 44px;
        box-sizing: border-box;
        background: white;
      }
    }
  }
}
</style>
